using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using OpenTK.Math;
using System.Collections;

namespace Dogfight2008.Common
{
  public class ColoredPolygon :IEnumerable<Vector3>
  {
    public readonly Color Color;
    public readonly FixedList<Vector3> Vertices;
    public readonly Vector3 Normal;

    public ColoredPolygon(Color color, IEnumerable<Vector3> vertices)
    {
      Color = color;
      Vertices = new FixedList<Vector3>(vertices);
      Normal = ComputeNormal();
    }

    private Vector3 ComputeNormal()
    {
      Random r = new Random();
      Vector3 v = new Vector3();
      float area = 0;
      do
      {
        int i1 = 0;
        int i2 = r.Next() % Vertices.Count;
        int i3 = r.Next() % Vertices.Count;
        if (i2 > i3)
        {
          int tmp = i2;
          i2 = i3;
          i3 = tmp;
        }
        Vector3 P1 = Vertices[i1];
        Vector3 P2 = Vertices[i2];
        Vector3 P3 = Vertices[i3];
        v = Vector3.Cross(P2 - P1, P3 - P1);
        area = v.Length;
      } while (area < 0.00001);
      v.Normalize();
      return v;
    }

    public ColoredPolygon(Color color, params Vector3[] vertices)
    {
      Color = color;
      Vertices = new FixedList<Vector3>(vertices);
    }

    public override string ToString()
    {
      return string.Format("{0} vertex polygon colored {1}", Vertices.Count, Color.ToString());
    }

    public override bool Equals(object obj)
    {
      ColoredPolygon rhs = obj as ColoredPolygon;
      if (rhs == null)
        return false;

      if (this.Color.R != rhs.Color.R)
        return false;

      if (this.Color.G != rhs.Color.G)
        return false;

      if (this.Color.B != rhs.Color.B)
        return false;

      return Vertices.Equals(rhs.Vertices);
    }

    public override int GetHashCode()
    {
      unchecked
      {
        return Color.GetHashCode() + Vertices.GetHashCode();
      }
    }

    #region IEnumerable<Vector3> Members

    public IEnumerator<Vector3> GetEnumerator()
    {
      return Vertices.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return Vertices.GetEnumerator();
    }

    #endregion
  }
}
